<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #carmsg="{ record }">
        <div class="car-msg">
          <div class="car-msg-left">
            <div class="col-lic">
              车牌号：{{ record.licenseNo || '-' }}
              <div v-if="record.modelPhoneUrl" class="col-img" @click="previewFn(record.modelPhoneUrl)">查看车辆图片</div>
            </div>
            <a-popover position="right">
              <div class="truncate">车型：{{ record.modelName || '-' }} </div>
              <template #content>
                {{ record.modelName || '-' }}
              </template>
            </a-popover>
            <div class="truncate">车架号：{{ record.vin || '-' }}</div>
          </div>
        </div>
      </template>
      <template #orderNo="{ record }">
        <div class="order-no-wrap" v-if="Array.isArray(record.orderList) && record.orderList.length > 0">
          <p class="order-no" v-for="(item, index) in record.orderList.slice(0, 2)" :key="index">{{ item }}</p>
          <p class="order-no more" v-if="record.orderList.length > 2" @mouseenter="moreOver(record)" @mouseleave="moreOut()">...</p>
        </div>
      </template>
    </table-index>
  </div>

  <a-image-preview-group v-model:visible="previewVisible" v-model:current="previewCurrent" :maskClosable="false" :srcList="previewList" />

  <!-- 添加费用弹框 -->
  <car-add-cost-modal ref="carAddModalRef" @ok="onCarAddModalOk" />

  <car-delete-modal v-model="deleteVisible" :data="tableRowRecord" @ok="loadData" />
</template>

<script setup name="DisposalCarList" lang="ts">
  import carAddCostModal from '../car-manage/components/car-add-cost-modal.vue'
  import carDeleteModal from '../car-manage/components/car-delete-modal.vue'

  import { onMounted, ref, reactive, computed, nextTick } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getDisposalCarList, cartoList, searchForStaff, updateOtherFee } from '@/api/asset/car'
  import useNavigate from '@/hooks/useNavigate'
  import { useRoute } from 'vue-router'
  import useUserStore from '@/store/modules/user'
  import { useSysDict, usePageDict } from '@/hooks/useDict'
  import usePermissionStore from '@/store/modules/permission'

  const permissionStore = usePermissionStore()
  // 根据商户是否开启etc和tbox来增加搜索条件和对应列
  const userStore = useUserStore()
  userStore.setEpDetail()

  const { navigateTo } = useNavigate()
  const route = useRoute()

  // 归属门店跳转后回显
  const oldId = ref(null)

  const carManageDict = usePageDict('carManageDict')
  useSysDict(['carInfo_driveNature', 'indicator_plate_type', 'car_index_property'])

  // 接口参数（不包含page信息）
  const queryParam = reactive({})
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input', maxlength: 10 },
      {
        label: '品牌',
        prop: 'brandId',
        type: 'remote-select',
        attrs: {
          type: 'search_car_brand',
          params: {
            id: queryParam.brandId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.brandId = option.id
          }
          queryParam.seriesId = ''
          queryParam.modelId = ''
        },
      },
      {
        label: '车系',
        prop: 'seriesId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenant_carList',
          params: {
            brandId: queryParam.brandId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.seriesId = option.id
          }
          queryParam.modelId = ''
        },
      },
      {
        label: '车型',
        prop: 'modelId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenantList',
          params: {
            seriesId: queryParam.seriesId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.modelId = option.id
          }
        },
      },
      {
        label: '归属门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
          params: {
            oldId: oldId.value,
          },
        },
      },
      {
        label: '车辆来源',
        prop: 'sourceIdList',
        type: 'a-select',
        multiple: true,
        options: carManageDict.disposalSourceEnumList,
      },
      {
        label: '车架号',
        prop: 'vin',
        type: 'a-input',
      },
    ]
  })

  const carAddModalRef = ref()
  const deleteVisible = ref(false)
  const tableRowRecord = ref()

  const table = useTable({
    columns: [
      { title: '车辆信息', dataIndex: 'carMsg', width: 240, fixed: 'left', slotName: 'carmsg' },
      { title: '归属门店', dataIndex: 'siteName', width: 150 },
      { title: '归属车场', dataIndex: 'libraryName' },
      { title: '车辆来源', dataIndex: 'sourceName' },
      { title: '运营状态', dataIndex: 'operateStatusName' },
      { title: '操作人', dataIndex: 'updateUser' },
      { title: '操作时间', dataIndex: 'updateTime', width: 170 },
    ],
    operates: [
      {
        label: '详情',
        permission: 'svms:asstes:car:car-disposal.detail',
        method: (record, column, rowIndex) => {
          console.log(record, column, rowIndex)
          navigateTo(`/car-manage/detail/${record.id}?from=car-disposal`, `${record.licenseNo}-车辆详情`)
        },
      },
      {
        label: '费用信息',
        permission: 'svms:asstes:car:car-disposal.cost',
        method: (record) => {
          navigateTo(`/car-manage/detail/${record.id}?tab=8&from=car-disposal`, `${record.licenseNo}-车辆详情`)
        },
      },
      {
        label: '添加费用',
        permission: 'svms:asstes:car:car-disposal.addcost',
        show: (record) => record.source !== 2,
        method: (record) => {
          console.log(record, 'record')
          carAddModalRef.value.open(record)
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:car:car-disposal.operaterecords',
        method: (record) => {
          navigateTo(`/car-manage/detail/${record.id}?tab=9&from=car-disposal`, `${record.licenseNo}-操作记录`)
        },
      },
      {
        label: '删除',
        show: () => permissionStore.getRoleList.some((item) => item.adminRole === 1),
        // permission: 'svms:asstes:car:car-disposal.delete',
        method: (record) => {
          deleteVisible.value = true
          tableRowRecord.value = record
        },
      },
    ],
  })

  // 列表接口调用
  const loadData = (page) => {
    const fn = useFetchTableDataApi(table, queryParam, getDisposalCarList)
    fn(page).then((result) => {
      console.log(result, 'result')
      result.data.forEach((item) => {
        if (item.orderList) {
          item.orderList.forEach((e) => {
            e.showTrigger = false
          })
        }
      })
    })
  }

  const previewVisible = ref(false)
  const previewCurrent = ref(0)
  const previewList = ref([])
  const previewFn = (url) => {
    previewCurrent.value = 0
    previewVisible.value = true
    previewList.value = [url]
  }

  const saveLicense = () => {
    console.log('change')
    loadData()
  }

  const onCarAddModalOk = (formRef, list, costInfo) => {
    formRef.value.validate((valid) => {
      if (!valid) {
        console.log(list, 'table.dataList')
        updateOtherFee({ carId: costInfo.id, operateType: 0, feeList: list }).then((res) => {
          console.log(res)
          carAddModalRef.value.close()
          navigateTo(`/car-manage/detail/${costInfo.id}?tab=8&from=car-disposal`, `${costInfo.licenseNo}-车辆详情`)
        })
      }
    })
  }

  // 获取参数
  const pageQueryList = ref({})
  const toPageList = () => {
    cartoList().then((res) => {
      pageQueryList.value = res.result
    })
  }

  // 获取门店
  const storeList = ref([])
  const toStoreList = () => {
    searchForStaff().then((res) => {
      res.result.map((e) => {
        e.value = e.id
        e.label = e.siteName
      })
      storeList.value = res.result
    })
  }

  defineExpose({
    saveLicense,
  })

  onMounted(() => {
    if (route.query.licenseNoLike) {
      queryParam.licenseNoLike = route.query.licenseNoLike
    }
    if (route.query.siteId) {
      queryParam.siteIdList = [route.query.siteId]
      nextTick(() => {
        oldId.value = route.query.siteId
      })
    }
    if (route.query.operateStatus) {
      queryParam.operateStatusList = [+route.query.operateStatus]
    }
    loadData()
    toPageList()
    toStoreList()
  })
</script>

<style lang="less" scoped>
  .a-link {
    color: rgba(24, 144, 255, 1);
  }
  .height-48 {
    height: 48px;
    overflow: hidden;
  }
  .trigger-box {
    display: flex;
    align-items: center;
    cursor: pointer;
    .open,
    .close {
      font-weight: 400;
      color: rgba(24, 144, 255, 1);
      font-size: 14px;
      margin-right: 4px;
    }
    .icon {
      color: rgba(24, 144, 255, 1);
    }
  }
  .car-msg-left {
    overflow: hidden;
  }
  .car-msg-img {
    width: 100px;
  }
  .col-lic {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    color: #1d2129;
    font-size: 14px;
    font-weight: 600;
  }
  .col-img {
    color: #165dff;
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
